import React, { useState, useEffect, useRef, FC } from 'react';
import { PageContainer, WaterMark } from '@ant-design/pro-layout';
import { Card, Button, message } from 'antd';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table'
import {
  UploadOutlined
} from '@ant-design/icons';
import { SingleVipCodeListType, CreateCodeType, ExpotCodeType } from './data'
import type { ListParamsType } from '@/services/data'
import { getVipCodeList, getSelectVipCodeList, createCode, expotCode } from './service';
import './index.less'
import CreateCode from './components/createcode'
import ExportJsonExcel from 'js-export-excel';

const VipCodeListPage: FC<any> = () => {
  const [mealOptions, setMealOptions] = useState<any>({});
  const [roleLists, setRoleList] = useState<SingleVipCodeListType[]>([]);
  const [loadings, setLoadings] = useState<boolean[]>([]);

  //配置ProTable
  const ref = useRef<ActionType>();
  //操作ProTable数据内容
  const formRef = useRef<FormInstance>();

  //相当于componentDidMount
  useEffect(() => {
    (async function onCreateFun() {
      const mealOptions = await getSelectVipCodeList()
      if (mealOptions && mealOptions instanceof Object) {
        for (let [key, value] of Object.entries(mealOptions.data.combo_map)) {
          mealOptions.data.combo_map[key] = { text: value, status: 'Default' }
        }
        setMealOptions(mealOptions.data.combo_map)
      }
    })();
  }, [])
  /**
   * ProTable的网络请求 request
   */
  const requestHandler = async (params: ListParamsType) => {
    const roleList = await getVipCodeList(params = { ...params, perpage: params.pageSize, page: params.current });
    if (roleList && roleList instanceof Object) {
      setRoleList(roleList.data.rows)
      return {
        data: roleList.data.rows,
        success: true,
        total: roleList.data?.total
      }
    }
    return {
      success: false,
    }
  }
  //创建邀请码
  const onCreateFinish = async (values: CreateCodeType) => {
    const response = await createCode(values)
    if (response && response instanceof Object) {
      message.success(response.message)
      return true
    }
    return false
  }
  //ModalForm状态改变
  const onVisibleChange = (value: boolean) => {
    if (!value) {
      setTimeout(() => {
        ref.current?.reload();
      }, 1000);
    }
  }

  //导出当前页面
  const onExportExNow = () => {
    const newLoadings = [...loadings]
    newLoadings[0] = true
    setLoadings(newLoadings)
    const option = {
      fileName: '下载文档',//excel文件名称
      datas: [
        {
          sheetData: roleLists,  //excel文件中的数据源
          sheetName: '活动',  //excel文件中sheet页名称
          sheetFilter: ['card_no', 'combo_name', 'mobile', 'combo_id',
            'duration_day', 'combo_price_str', 'active_status', 'active_time_str',
            'ctime_str'],// excel文件中需显示的列数据
          sheetHeader: ['卡号', '套餐用户', '激活用户', '选择套餐',
            '套餐时长', '套餐价格', '状态', '使用时间',
            '创建时间'],  //excel文件中每列的表头名称
        }
      ]
    };  //option代表的就是excel文件
    let toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
    newLoadings[0] = false
    setLoadings([...newLoadings])
  }

  //后台导出
  const onExportSort = async () => {
    const newLoadings = [...loadings]
    let params: ExpotCodeType = formRef.current?.getFieldsValue()
    const { card_no, combo_id, ctime_str, mobile } = params

    if (!((card_no || combo_id || mobile || ctime_str[0] || ctime_str[1]) || false)) {
      message.error('请至少选择一项筛选条件才能导出')
      return;
    }
    newLoadings[1] = true
    setLoadings(newLoadings)
    try {
      const response = await expotCode(params = { ...params, start_time: params.ctime_str[0], end_time: params.ctime_str[1], ctime_str: undefined });
      message.success(response.message)
    } catch (error) {
      message.error("导出失败")
    }
    newLoadings[1] = false
    setLoadings([...newLoadings])
  }

  const columns: ProColumns<SingleVipCodeListType>[] = [
    {
      title: '卡号',
      dataIndex: 'card_no',
      width: 128,
      align: 'left'
    },
    {
      title: '套餐用户',
      dataIndex: 'combo_name',
      ellipsis: true,
      align: 'left',
      search: false,
    },
    {
      title: '激活用户',
      dataIndex: 'mobile',
      hideInTable: true,
    },
    {
      title: '选择套餐',
      dataIndex: 'combo_id',
      hideInTable: true,
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: mealOptions,
    },
    {
      title: '套餐时长',
      dataIndex: 'duration_day',
      ellipsis: true,
      search: false,
      align: 'left'
    },

    {
      title: '套餐价格',
      dataIndex: 'combo_price_str',
      ellipsis: true,
      search: false,
      align: 'left'
    },
    {
      title: '状态',
      dataIndex: 'active_status',
      search: false,
      align: 'left',
      render: (text) => <span className={text === 1 ? `activated` : `no-use`}>{text === 1 ? `已激活` : `未使用`}</span>,
    },
    {
      title: '使用时间',
      dataIndex: 'active_time_str',
      search: false,
      align: 'left'
    },
    {
      title: '创建时间',
      dataIndex: 'ctime_str',
      search: false,
      align: 'left'
    },
    {
      title: '创建时间',
      dataIndex: 'ctime_str',
      valueType: 'dateTimeRange',
      hideInTable: true,
      colSize: 2,
      search: {
        transform: (value) => {
          console.log(value)
          return {
            start_time: value[0],
            end_time: value[1],
          };
        },
      },
    },
  ];

  return (
    <PageContainer>
      <Card>
        <WaterMark content="御码科技">
          <ProTable
            request={requestHandler}
            actionRef={ref}
            formRef={formRef}
            columns={columns}
            rowKey="id"
            search={{
              labelWidth: 'auto',
            }}
            pagination={{
              showQuickJumper: true,
              pageSize: 10,
            }}
            form={{
              // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
              syncToUrl: (values, type) => {
                if (type === 'get') {
                  return {
                    ...values,
                    ctime_str: [values.start_time, values.end_time],
                  };
                }
                return values;
              },
              span: 6
            }}
            toolBarRender={() => [
              <Button icon={<UploadOutlined />} loading={loadings[0]} type="primary" onClick={onExportExNow}>
                导出excel(当前页面)
              </Button>,
              <Button icon={<UploadOutlined />} loading={loadings[1]} type="primary" onClick={onExportSort}>
                导出excel(根据选择条件)
              </Button>,
              <CreateCode
                mealOptions={mealOptions}
                onCreateFinish={onCreateFinish}
                onVisibleChange={onVisibleChange} />
            ]}
          />
        </WaterMark>
      </Card>
    </PageContainer>
  )
}
export default VipCodeListPage